package com.jzo2o.orders.manager.listener;

import cn.hutool.core.convert.Convert;
import com.jzo2o.api.orders.dto.request.OrderCancelReqDTO;
import com.jzo2o.api.orders.dto.response.OrderResDTO;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * \* User: chy
 * \* Date: 2025/10/7  13:55
 * \* Description:订单超时未支付
 * \
 */
@Component
@Slf4j
public class OrderTimeoutListener {
    @Resource
    private IOrdersManagerService  ordersManagerService;

    /**
     * 订单超时未支付
     *
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "order.timeout", durable = "true"),//队列名字,持久化
            exchange = @Exchange(name = "order-exchange",delayed = "true"),//延迟交换机
            key = "order-timeout-queue"
    ))
    public void orderTimeout(String msg) {
        try {
            log.info("订单超时未支付的订单id：{}", msg);
            if (!StringUtils.hasText(msg)) {
                return;
            }
            // 查询订单详情
            Long orderId = Convert.toLong(msg);
            OrderResDTO resDTO = ordersManagerService.getDetail(orderId);
            if(resDTO == null || resDTO.getOrdersStatus() != 0){
                return;
            }
            // 取消订单
            OrderCancelReqDTO reqDTO = new OrderCancelReqDTO();
            reqDTO.setId(orderId);
            reqDTO.setCancelReason("订单15分钟未支付取消");
            ordersManagerService.cancelOrder(reqDTO);
        } catch (Exception e) {
            log.error("订单超时未支付异常：{}", e);
        }
    }
}
